{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "F:\\anaconda\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    }
   ],
   "source": [
    "#from __future__ import absolute_import\n",
    "#from __future__ import division\n",
    "#from __future__ import print_function\n",
    "#import argparse\n",
    "#import sys\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "import tensorflow as tf\n",
    "#FLAGS=None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-410a18ecea24>:2: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From F:\\anaconda\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From F:\\anaconda\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting C:\\Users\\Administrator\\AI8\\w6\\data\\train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From F:\\anaconda\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting C:\\Users\\Administrator\\AI8\\w6\\data\\train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From F:\\anaconda\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting C:\\Users\\Administrator\\AI8\\w6\\data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting C:\\Users\\Administrator\\AI8\\w6\\data\\t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From F:\\anaconda\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "mnist_dir=\"C:\\\\Users\\\\Administrator\\\\AI8\\\\w6\\\\data\"\n",
    "mnist=input_data.read_data_sets(mnist_dir,one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义神经网络的待优化参数w、正则L2优化w值\n",
    "def get_weight(shape, regularizer):\n",
    "    w = tf.Variable(tf.random_normal(shape), dtype=tf.float32)\n",
    "    tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))\n",
    "    return w"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "x=tf.placeholder(tf.float32,[None,784])   #输入数据结构\n",
    "H_NN1=600\n",
    "H_NN2=784\n",
    "#定义参数变量结构\n",
    "#w1=tf.Variable(tf.random_normal([784,H_NN1]))  \n",
    "w1 = get_weight([784,H_NN1], 0.1)\n",
    "b1=tf.Variable(tf.random_normal([H_NN1]))\n",
    "#y=tf.matmul(x,w)+b\n",
    "#隐层和输出层\n",
    "h1=tf.nn.sigmoid(tf.matmul(x,w1)+b1)   #隐层1\n",
    "#w2=tf.Variable(tf.random_normal([H_NN,10]))  \n",
    "w2 = get_weight([H_NN1,H_NN2], 0.1)\n",
    "b2=tf.Variable(tf.random_normal([H_NN2]))\n",
    "h2=tf.nn.sigmoid(tf.matmul(h1,w2)+b2)   #隐层2\n",
    "#w2=tf.Variable(tf.random_normal([H_NN,10]))  \n",
    "w3 = get_weight([H_NN2,10], 0.1)\n",
    "b3=tf.Variable(tf.random_normal([10]))\n",
    "y=tf.matmul(h2,w3)+b3\n",
    "#y=tf.nn.softmax(tf.matmul(h1,w2)+b2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_=tf.placeholder(tf.float32,[None,10])   #输出结构\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 损失函数\n",
    "cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_,logits=y))\n",
    "#loss=tf.reduce_mean(tf.square(y-y_))\n",
    "#New loss\n",
    "#cross_entropy = loss + tf.add_n(tf.get_collection('losses'))\n",
    "# 下降方法 梯度下降 参数表示训练效率,通常小于1，实践发现参数不能太大，参数太大会导致无法得到正确的训练结果\n",
    "learning_rate=0.9\n",
    "train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)  #优化目标，使损失最小化\n",
    "\n",
    "init_op=tf.global_variables_initializer()   # 初始所有变量，这个必须要有\n",
    "sess=tf.Session()\n",
    "sess.run(init_op)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "for _ in range(3000):\n",
    "    batch_xs,batch_ys=mnist.train.next_batch(100)\n",
    "    sess.run(train_step,feed_dict={x:batch_xs,\n",
    "                                  y_:batch_ys})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9434\n"
     ]
    }
   ],
   "source": [
    "correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))\n",
    "accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "print(sess.run(accuracy,feed_dict={x:mnist.test.images,\n",
    "                                  y_:mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
